package cn.zd.core.utils;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * Http工具类
 *
 * @author TMAC
 * @email 2466721401@qq.com
 */
public class HttpUtils {

    /**
     * 默认的字符集
     */
    public static final String CharSet = "UTF-8";

    /**
     * 向客户端写入文本
     *
     * @param response
     * @param text
     */
    public static void writeText(HttpServletResponse response, String text) {
        response.setCharacterEncoding(CharSet);
        response.setContentType("text/html;charset=UTF-8");
        try {
            response.getWriter().write(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向客户端写入JSON数据
     *
     * @param response
     * @param obj
     */
    public static void writeJson(HttpServletResponse response, Object obj) {
        String json = null;
        if (obj instanceof String) {
            json = (String) obj;
        } else {
            json = JsonUtils.toJSON(obj);
        }

        response.setCharacterEncoding(CharSet);
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
